// 表单card折叠hook，并滚动到错误信息位置
import { scroll2el } from '@/utils/scroll2el'

interface FoldItem {
  key: string
  props: string[]
}
interface errorItem {
  message: string
  field: string
}
// const cardList = [
//   {
//     key: 'card1',
//     props: ['a','b','c'],
//   },
// ]
// const errors = [
//   {message: '请输入', field: 'price'}
// ]

import { reactive, nextTick } from 'vue'

const isContainField = (errFields: any, targetField: string) => {
  return errFields.some((item) => targetField == item || targetField.indexOf(item) >= 0)
}

export default function useFormFold(list: FoldItem[]) {
  const foldStatus = reactive({}) as any
  // 初始化 foldStatus
  list.forEach((it: any) => {
    foldStatus[it.key] = true
  })
  const foldValidate = (errors: errorItem[], scrollToErr = false) => {
    // 没错直接去提交不修改折叠状态
    if (!errors || errors.length == 0) {
      return
    }
    const errFields = errors.map((it: any) => it.field)

    list.forEach((it: any) => {
      if (it.props) {
        // 全对则收起
        let initValue = false
        it.props.forEach((prop: string) => {
          if (isContainField(errFields, prop)) {
            initValue = true
          }
        })
        foldStatus[it.key] = initValue
      }
    })

    if (scrollToErr) {
      scroll2el('.ve-form-item__body__right__message')
    }
  }

  const foldAddItem = (item: any) => {
    list.push(item)
    foldStatus[item.key] = item.value
  }
  return {
    foldStatus,
    foldValidate,
    foldAddItem,
  }
}
